﻿var updateVersion = localStorage["__updateMessage"];

if (localStorage["__shouldCacheMisses"] === undefined && updateVersion === undefined) {
  window.open("installed.html", "_blank", "width=600px,height=400px");
}

var exclusionSites = ["blogspot", "royalmail", "linkedin"];

chrome.extension.onRequest.addListener(handleRequest);

var redirectFunctions = []; // tabId -> function(bool)

function checkForSecureVersion(tabId, url, hostname, redirect, incognito, retryFull) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {
        showPageAction(tabId, url, hostname, redirect);
      } else {
        if (!retryFull && this.status == 405) {
          checkForSecureVersion(tabId, url, hostname, redirect, incognito, true);
          return;
        }
        if (shouldSaveNoneExists(incognito)) {
          saveResult(tabId, url, hostname, "defaultfalse", redirect);
        }
      }
    }
  };
  xhr.open(retryFull ? "GET" : "HEAD", url, true);
  xhr.send("");
}

function showPageAction(tabId, url, hostname, redirect) {
  chrome.pageAction.setPopup({tabId: tabId, popup: "popup.html?tabId=" + tabId + "&hostname=" + hostname + "&site=" + url});
  redirectFunctions[tabId] = redirect;
  chrome.pageAction.show(tabId);
}

function shouldLookupUnknown(incognito) {
  return incognito === undefined || incognito === false;
}

function shouldSaveNoneExists(incognito) {
  return localStorage["__shouldCacheMisses"] === "true" && (incognito === undefined || incognito === false);
}

function isExcluded(url, hostname) {
  if (/^(www\.)*google\.[A-Za-z.]+$/i.test(hostname)) {
    if (/^http:\/\/(www\.)*google\.[A-Za-z.]+\/(calendar|voice|reader)/i.test(url)) {
      if (localStorage[hostname] == "defaultfalse") {
        localStorage.removeItem(hostname);
      }
      return false;
    }
    return true;
  }
  for (site in exclusionSites) {
    var re = new RegExp("(.*\\.)*" + exclusionSites[site] + "\\.[A-Za-z.]+", "i");
    if (re.test(hostname)) {
      return true;
    }
  }
  return false;
}

/**
 * redirect = function(shouldRedirect: bool)
 */
function checkTab(tab, location, redirect) {
  if (isExcluded(tab.url, location.hostname)) {
    redirect(false);
    return;
  }
  
  if (tab.url.substring(0, 5) === "http:") {
    var newUrl = "https" + tab.url.substring(4);
    if (localStorage[location.href] === "true") {
      redirect(true);
      return;
    }
    var localStorageValue = localStorage[location.hostname];
    if (localStorageValue === undefined && shouldLookupUnknown(tab.incognito)) {
      checkForSecureVersion(tab.id, newUrl, location.hostname, redirect, tab.incognito, false);
      return;
    } else if (localStorageValue === "true") {
      redirect(true);
    }
  }
  chrome.pageAction.hide(tab.id);
}

/**
 * Expected requests:
 * {request: "popup", hostname="foo.bar", redirect: boolean, site: "https://...", tabId: integer}
 * {request: "probe", location: window.location}
 */
function handleRequest(request, sender, sendResponse) {
  if (request.request == "popup") {
    sendResponse({});
    saveResult(request.tabId, request.site, request.hostname, request.redirect);
  } else if (request.request == "probe") {
    checkTab(sender.tab, request.location, function(shouldRedirect) {sendResponse({redirect: shouldRedirect});});
  }
}

function saveResult(tabId, url, hostname, result, redirect) {
  chrome.pageAction.hide(tabId);
  localStorage[hostname] = result;
  if (redirect === undefined) {
    redirect = redirectFunctions[tabId];
    redirectFunctions[tabId] = undefined;
  }
  redirect(result == true);
}